package top.xzxsrq.freemarker.utils;

/**
 * @program: MyUtils
 * @description:
 * @author: 致心
 * @create: 2021-03-11 15:38
 **/

import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import top.xzxsrq.common.utils.FileUtilsZX;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Created by Ay on 2016/7/27.
 */
public class FreeMarkerTemplateUtils {

    private FreeMarkerTemplateUtils() {
    }

    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_31);

    static {
        //这里比较重要，用来指定加载模板所在的路径
        CONFIGURATION.setClassForTemplateLoading(FreeMarkerTemplateUtils.class, "/templates");
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    /**
     * @param templateName
     * @return
     * @throws IOException
     * @Description :获取resource文件夹下的templates文件夹下的文件
     * @Author :致心
     * @Date :2021/5/8 9:26
     */
    public static Template getTemplate(String templateName) throws IOException {
        return CONFIGURATION.getTemplate(templateName);
    }

    public static void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }

    /**
     * @param template 获取用例模板
     * @param data     传进来的数据
     * @param filePath 生成文件的路径 绝对路径
     * @throws IOException
     * @throws TemplateException
     * @Description :
     * @Author :致心
     * @Date :2021/3/15 10:53
     */
    public static void generate(Template template, Object data, String filePath) throws IOException, TemplateException {
        File file = FileUtilsZX.createFile(filePath);
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8), 10240);
        template.process(data, out);
    }
}
